import React, { forwardRef, useEffect, useImperativeHandle, useState } from 'react';
import Modals from '@/components/modals/Modals';
import { Form, Input, Button, Avatar, Tag, Switch, Tooltip, ModalProps, message } from 'antd';
import './index.scss';
import {
  EyeInvisibleOutlined,
  EyeTwoTone,
  LoadingOutlined,
  PlusOutlined,
  SettingOutlined,
} from '@ant-design/icons';
import { GetCreatedListItem, GetModelListModels, GetProviderListItem } from '@/common/types';
import useTable from '@/hooks/use-table';
import modelService from '@/api/services/modelService';
import { SvgIcon } from '@/components/icon';
import { CircleLoading } from '@/components/loading';
import { fetchEventSource } from '@fortaine/fetch-event-source';
import useModal from '@/hooks/use-modal/useModal';
import ModelCloseTips from '../ModelCloseTips';
import ModalsBoxContent from '@/components/modals/ModalsBoxContent';

interface Props extends ModalProps {
  open: boolean;
  onCancel: (updateStatus?: boolean) => void;
  onSubmit: (updateStatus?: boolean) => void;
  modelData: GetProviderListItem | GetCreatedListItem | undefined;
  updateModel: (value: any, list?: any) => void;
  refresh: number;
  openSetting: (item: GetModelListModels) => void;
  status: boolean;
  okText?: string;
  title?: string;
  onClose?: () => void;
  updateTables?: () => void;
  customStatus?: boolean;
}

interface GetModelListModelsTime extends GetModelListModels {
  time?: number;
  timeStatus?: boolean;
  timeLoading?: boolean;
  timeMsg?: string;
}

const modelTitle = {
  llm: '语言模型',
  funcCall: '工具调用模型',
  rerank: '重排模型',
  embedding: '索引模型',
  non: '非默认模型',
  tt: '语音模型',
  stt: '语音转文本模型',
  tts: '文本转语音模型',
};

const index = forwardRef(
  (
    {
      modelData,
      updateModel,
      onCancel,
      refresh,
      openSetting,
      onSubmit,
      status,
      okText,
      title,
      onClose,
      updateTables,
      customStatus,
      ...props
    }: Props,
    ref,
  ) => {
    const {
      tablesValue,
      loading: tablesLoading,
      getTables,
      pagingInfo,
      handleSearchText,
      searchText,
      setTablesValue,
    } = useTable<GetModelListModelsTime>(modelService.getModelList);

    const modals = useModal('close');

    const [verticalStatus, setVerticalStatus] = useState(false);

    const [verticalLoading, setVerticalLoading] = useState(false);

    const [form] = Form.useForm();

    const [loading, setLoading] = useState<string>('');

    const [selectValue, setSelectValue] = useState<GetModelListModels>();

    const [errorMsg, setErrorMsg] = useState<string>('');

    const [testStatus, setTestStatus] = useState<boolean>(false);

    useImperativeHandle(ref, () => ({
      setTablesValue,
    }));

    useEffect(() => {
      console.log('modelData', modelData);

      if (modelData && props.open && !customStatus) {
        getTables({
          page: 1,
          pageSize: 999,
          searchText: '',
          provider: [modelData.isLocal ? 'Ruijie' : modelData.name],
          isRecommend: !status,
        });
        form.setFieldsValue({
          key: modelData?.key,
          baseUrl: modelData?.baseUrl,
          name: modelData.name,
        });
        setVerticalStatus(false);
      } else {
        setTablesValue([]);
        form.resetFields();
      }
    }, [modelData, props.open, customStatus]);

    useEffect(() => {
      if (refresh) {
        getTables({ ...pagingInfo, provider: [modelData.name] });
        setVerticalStatus(false);
      }
    }, [refresh]);

    const handleActive = (record: GetModelListModels) => {
      setSelectValue(record);

      if (record.usedCount > 0 && record.metadata.isActive) {
        modals.close.open();
        return;
      }
      updateModels(record);
    };

    const updateModels = (record: GetModelListModelsTime) => {
      setTablesValue((prev) => {
        return prev.map((item) => {
          if (item.metadata.model === record.metadata.model) {
            return {
              ...item,
              metadata: {
                ...item.metadata,
                isActive: !record.metadata.isActive,
              },
            };
          }
          return item;
        });
      });
      modals.close.close();
    };

    const handleOk = () => {
      if (selectValue) {
        updateModels(selectValue);
      }
    };

    const handleApiVerify = (value: any) => {
      if (customStatus) {
        const result = tablesValue.map((item) => ({
          modelType: item.metadata.modelType,
          name: item.metadata.name,
          maxContext: item.metadata.maxContext,
          maxResponse: item.metadata.maxResponse,
          usedInToolCall: item.metadata.usedInToolCall,
          enableReasoning: item.metadata.enableReasoning,
          isActive: item.metadata.isActive,
        }));

        modelService
          .createCustom({
            name: value.name,
            key: value.key,
            address: value.baseUrl,
            models: result,
          })
          .then((res) => {
            if (res) {
              setErrorMsg(res);
              setVerticalStatus(true);
              return;
            }

            setVerticalStatus(false);
            onSubmit(true);
          });
        return;
      }

      if (modelData?.isLocal) {
        onCancel();
        return;
      }

      const activateModels = tablesValue
        .filter((item) => item.metadata.isActive)
        .map((item) => ({ name: item.metadata.model, type: item.metadata.type }));

      setVerticalLoading(true);

      const data = {
        name: modelData?.isThirdParty ? value.name : (modelData?.name as string),
        key: value.key,
        address: value.baseUrl,
        activateModels,
      };

      if (status) {
        modelService
          .updateProvider(modelData?.id as string, data)
          .then((res) => {
            if (res) {
              setErrorMsg(res);
              setVerticalStatus(true);
              return;
            }

            setVerticalStatus(false);
            // onCancel(true);
            onSubmit(true);
          })
          .finally(() => {
            setVerticalLoading(false);
          });
      } else {
        modelService
          .createProvider(data)
          .then((res) => {
            if (res) {
              setErrorMsg(res);
              setVerticalStatus(true);
              return;
            }

            setVerticalStatus(false);
            onSubmit(true);
            // onCancel(true);
          })
          .finally(() => {
            setVerticalLoading(false);
          });
      }
    };

    const init = () => {
      // setLoading(false);
      setVerticalLoading(false);
      setVerticalStatus(false);
      onCancel();
    };

    const handleSetting = (item: GetModelListModels) => {
      openSetting(item);
    };

    const handleBatchTest = async () => {
      const value = form.getFieldsValue();

      if (!value.key || !value.baseUrl) {
        message.error('请填写API密钥或API地址');
        // address key
        return;
      }

      setTestStatus(true);
      const test = {
        modelList: tablesValue.map((item) => ({
          model: item.metadata.model,
          type: item.metadata.type,
        })),
        address: value.baseUrl,
        key: value.key,
      };

      setTablesValue((prev) => {
        return prev.map((item) => ({ ...item, timeLoading: true }));
      });

      await fetchEventSource('/openapi/v2/models/batch/test', {
        method: 'POST',
        body: JSON.stringify(test),
        headers: {
          'Content-Type': 'application/json',
        },

        onmessage({ event, data }) {
          const result = JSON.parse(data);
          if (result.type === 'providerError') {
            setTablesValue((prev) => {
              return prev.map((item) => {
                return {
                  ...item,
                  timeLoading: false,
                  time: 0,
                  timeStatus: false,
                  timeMsg: result.message,
                };
              });
            });
            return;
          }

          if (result.result !== undefined) {
            setTablesValue((prev) => {
              return prev.map((item) => {
                if (item.metadata.model === result.model) {
                  return {
                    ...item,
                    timeLoading: false,
                    time: result.duration ? result.duration : 0,
                    timeStatus: result.result ? result.result : undefined,
                    timeMsg: result.message,
                  };
                }

                return item;
              });
            });
          }
        },
        // onclose() {},
        onerror(err) {
          console.log('err', err);
        },
        openWhenHidden: true,
      });
    };

    const openNewWindos = () => {
      window.open(modelData?.officialUrl as string, '_blank');
    };

    const handleOpenChange = (value: boolean) => {
      if (!value && testStatus && updateTables) {
        updateTables();
        setTestStatus(false);
      }
    };

    return (
      <Modals
        title={title ? title : modelData?.isLocal ? '查看' : '输入信息'}
        onOk={modelData?.isLocal ? init : form.submit}
        onCancel={init}
        {...props}
        width={modelData?.isLocal ? 550 : 720}
        confirmLoading={verticalLoading}
        footerCancelHidden={modelData?.isLocal}
        okText={okText ? okText : modelData?.isLocal ? '关闭' : '确认'}
        onClose={onClose}
        modelContentClassName="!mr-0 !pr-0"
        afterOpenChange={handleOpenChange}
        footerOkDisabled={tablesLoading || tablesValue.length === 0}
      >
        {verticalStatus && (
          <div className="mb-2 mr-6 flex items-center rounded-md border-[1px] border-solid border-@error-color py-1 text-xs leading-5 text-@error-color">
            <SvgIcon icon="warning" size={16} className="mx-2" color="#FC5151" />
            <div>{errorMsg}</div>
          </div>
        )}

        {!modelData?.isLocal && (
          <Form layout="vertical" className="form !mr-6" form={form} onFinish={handleApiVerify}>
            {modelData?.isThirdParty && (
              <Form.Item
                label="厂商名称"
                rules={[{ required: true, message: '请输入厂商名称!' }]}
                name={'name'}
              >
                <Input />
              </Form.Item>
            )}
            <Form.Item
              label={
                <div className="flex w-full items-center justify-between">
                  <div>API密钥</div>
                  {!modelData?.isThirdParty && (
                    <Button type="link" className="!p-0" onClick={openNewWindos}>
                      从供应商获取API 秘钥
                    </Button>
                  )}
                </div>
              }
              rules={[{ required: true, message: '请输入API密钥!' }]}
              name={'key'}
              className="custom-label-layout"
            >
              <Input.Password
                placeholder="请输入API密钥"
                iconRender={(visible) => (visible ? <EyeTwoTone /> : <EyeInvisibleOutlined />)}
                visibilityToggle={{
                  visible: false,
                }}
              />
            </Form.Item>
            <Form.Item
              label="API地址"
              rules={[{ required: true, message: '请输入API地址!' }]}
              name={'baseUrl'}
            >
              <Input />
            </Form.Item>
          </Form>
        )}

        <div className="mb-2 mr-6 flex items-center justify-between">
          <div className="text-text-4">模型列表({tablesValue.length})</div>
          {(!modelData?.isLocal || (tablesValue.length !== 0 && customStatus)) && (
            <div>
              {status && (
                <Button
                  type="text"
                  icon={<PlusOutlined />}
                  onClick={() => {
                    const value = form.getFieldsValue();
                    if (!value.key || !value.baseUrl) {
                      message.error('请填写API密钥或API地址');
                      return;
                    }

                    updateModel(value);
                  }}
                >
                  添加模型
                </Button>
              )}
              {tablesValue.length !== 0 && (
                <Button type="text" className="ml-3" onClick={handleBatchTest}>
                  测试
                </Button>
              )}
            </div>
          )}
        </div>

        {customStatus && tablesValue.length === 0 ? (
          <div
            className="mr-6 flex h-[94px] cursor-pointer flex-col items-center justify-center gap-1 rounded-lg bg-[#ECEFF8] text-[#474C5F]"
            style={{
              width: 'calc(100% - 24px)',
            }}
            onClick={() => {
              const value = form.getFieldsValue();
              if (!value.key || !value.baseUrl) {
                message.error('请填写API密钥或API地址');
                return;
              }

              updateModel(value);
            }}
          >
            <PlusOutlined style={{ fontSize: 24 }} />
            <div>添加模型</div>
          </div>
        ) : (
          <ModalsBoxContent
            className={`flex max-h-[350px] min-h-[176px] flex-col gap-3 ${
              tablesValue.length > 0 ? ' overflow-y-auto' : ''
            }`}
          >
            {tablesLoading ? (
              <div className="h-[176px]">
                <CircleLoading />
              </div>
            ) : (
              tablesValue.map((item, index) => {
                let timeValue = '未测试';
                let timeRoundColor = 'bg-fill-5';

                if (item.time === undefined) {
                  timeValue = '未测试';
                  timeRoundColor = 'bg-fill-5';
                }

                if (item.time !== undefined && item.timeStatus) {
                  timeValue = `${item.time}s响应`;
                  timeRoundColor = 'bg-@success-color';
                }

                if (item.time !== undefined && !item.timeStatus) {
                  timeValue = '失效';
                  timeRoundColor = 'bg-@error-color';
                }
                return (
                  <div className="flex w-full items-center gap-2" key={index.toString()}>
                    <div className="flex items-center">
                      <SvgIcon
                        icon={
                          (modelData?.avatar as string) === 'Custom'
                            ? 'CustomModel'
                            : (modelData?.avatar as string)
                        }
                        size={24}
                        color="#E5E6EB"
                      />
                      <div className="ml-1 w-[200px] truncate">{item?.metadata.model}</div>
                    </div>

                    <div className="flex flex-1 gap-1">
                      {item.metadata.type && (
                        <div className="rounded-[4px] border-[1px] border-solid border-line-3 px-2 text-xs leading-5 text-text-3">
                          {modelTitle[item.metadata.type]
                            ? modelTitle[item.metadata.type]
                            : item.metadata.type}
                        </div>
                      )}
                      {item.metadata.reasoning && (
                        <div className="rounded-[4px] border-[1px] border-solid border-line-3 px-2 text-xs leading-5 text-text-3">
                          深度思考
                        </div>
                      )}
                      {item.metadata.usedInToolCall && (
                        <div className="rounded-[4px] border-[1px] border-solid border-line-3 px-2 text-xs leading-5 text-text-3">
                          工具调用
                        </div>
                      )}
                      {item.metadata.maxContext > 0 && (
                        <div className="rounded-[4px] border-[1px] border-solid border-line-3 px-2 text-xs leading-5 text-text-3">
                          {item.metadata.maxContext >= 1000
                            ? `${item.metadata.maxContext / 1000}K`
                            : item.metadata.maxContext}
                        </div>
                      )}
                    </div>

                    {!item.metadata.isLocal && (
                      <>
                        {
                          item.timeLoading ? (
                            <div className="flex w-20 items-center justify-center">
                              <LoadingOutlined className="text-base text-@brand-color" />
                            </div>
                          ) : item.time !== undefined && !item.timeStatus ? (
                            <Tooltip title={item.timeMsg}>
                              <div className="flex w-20 cursor-pointer items-center gap-1">
                                <div className={`h-[6px] w-[6px] rounded-full ${timeRoundColor}`} />
                                <div className="w-[70px]">{timeValue}</div>
                              </div>
                            </Tooltip>
                          ) : (
                            <div className="flex w-20 items-center gap-1">
                              <div className={`h-[6px] w-[6px] rounded-full ${timeRoundColor}`} />
                              <div className="w-[70px]">{timeValue}</div>
                            </div>
                          )
                          // <CircleLoading />
                        }

                        <div className="flex w-4 items-center justify-center">
                          {item.metadata.isCustom && (
                            <SvgIcon
                              icon="setting"
                              color="#1B6DFA"
                              size={16}
                              onClick={() => {
                                const value = form.getFieldsValue();
                                if (!value.key || !value.baseUrl) {
                                  message.error('请填写API密钥或API地址');
                                  return;
                                }
                                openSetting(item);
                                updateModel(value, tablesValue);
                              }}
                              className="cursor-pointer"
                            />
                          )}
                        </div>

                        {item.metadata.isLocal ? (
                          <Tooltip placement="topRight" title={'模型为默认模型无法关闭'}>
                            <Switch
                              value={item?.metadata.isActive}
                              onClick={() => handleActive(item)}
                              loading={item.id === loading}
                              disabled={item.metadata.isLocal}
                            />
                          </Tooltip>
                        ) : (
                          <Switch
                            value={item?.metadata.isActive}
                            onClick={() => handleActive(item)}
                            loading={item.id === loading}
                          />
                        )}
                      </>
                    )}
                  </div>
                );
              })
            )}
          </ModalsBoxContent>
        )}

        <ModelCloseTips
          open={modals.close.isOpen}
          onCancel={modals.close.close}
          onOk={handleOk}
          usedCount={selectValue?.usedCount || 0}
        />
      </Modals>
    );
  },
);

export default index;
